package org.lex.app.prefs;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Arrays;
import java.util.Properties;
import java.util.Set;

import org.lex.io.IO;


/**
 * @author Daniel Liu
 */
public class PropertyFileResourceMap extends AbstractFileBasedResourceMap {
	private Properties properties = null;

	public PropertyFileResourceMap(String file) {
		this(new File(file));
	}

	public PropertyFileResourceMap(File file) {
		super(file);
		this.properties = new Properties();
	}

	/**
	 * Searches for the property with the specified key. <br>
	 * The method returns <code>null</code> if the property is not found.
	 * 
	 * @param key
	 *            the property key.
	 * @return the value with the specified key value. or null
	 */
	@Override
	public String getString(String key) {
		return properties.getProperty(key);
	}

	@Override
	public void putString(String key, String value) {
		properties.setProperty(key, value);
	}

	@Override
	public void clear() {
		this.properties.clear();
	}

	@Override
	public boolean containsProperty(String key) {
		return this.properties.containsKey(key);
	}

	public Set<String> propertyNames() {
		return properties.stringPropertyNames();
	}

	public void load() throws IOException {
		InputStream in = null;
		try {
			in = this.openInputStream();
			this.properties.load(in);
		} catch (IOException e) {
			IO.closeQuietly(in);
			throw e;
		}
	}

	public void store() throws IOException {
		OutputStream out = null;
		try {
			out = this.openOutputStream();
			properties.store(out, this.getComment());
		} catch (IOException e) {
			IO.closeQuietly(out);
			throw e;
		}
	}

	@Override
	public String toString() {
		return this.toString("", "\n", "");
	}

	public String toString(String prefix, String sep, String suffix) {
		StringBuilder buffer = new StringBuilder();
		buffer.append(prefix);
		String[] keys = this.propertyNames().toArray(new String[0]);
		Arrays.sort(keys);
		for (int i = 0; i < keys.length; i++) {
			String key = keys[i];
			buffer.append(key).append(" = ");
			buffer.append(properties.getProperty(key));
			if (i < keys.length - 1)
				buffer.append(sep);
		}
		buffer.append(suffix);
		return buffer.toString();
	}
}
